﻿using System.Web.Helpers;
using System.Web.Mvc;

namespace Yz.Mvc.Filters
{
    public class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            if (request.IsAjaxRequest())
            {
                string strUserAgent = request.UserAgent.ToLower();
                if (strUserAgent.IndexOf("micromessenger") == -1)
                {
                    var cookieToken = request.Cookies[AntiForgeryConfig.CookieName];
                    string antiCookieToken = cookieToken != null ? cookieToken.Value : "";
                    string antiHeaderToken = request.Headers["__RequestVerificationToken"];
                    AntiForgery.Validate(antiCookieToken, antiHeaderToken);
                }
            }
        }
    }
}